import 'package:flutter/material.dart';
import './client_dio.dart';
import 'dart:convert';
import 'dart:core';
import './routes/align.dart';
import "item_edit.dart";
import "item_args.dart";
import './items_new.dart';
import './item_screens.dart';
class ItemsHome extends StatefulWidget {
  @override
  State createState() => new ItemsHomeState();
}
class ItemsHomeState extends State<ItemsHome> {
  var start=0;
  var limit=10;
  var total=0;
  var res;
  var query="";
  var rows=[TableRow(
              decoration: BoxDecoration(color: Colors.grey[200]),
              children: 
                [
                  Text("id"),
                  Text("bh"),
                  Text("name"),
                  Text("规格"),
                  Text("单位"),
                  Text("op"),
                ]
              )];
  final TextEditingController t1 = new TextEditingController(text: "0");
  final TextEditingController t2 = new TextEditingController(text: "0");
  final TextEditingController at_Controller = new TextEditingController(text:"1");
  TextEditingController search_Controller = new TextEditingController();
  //TextEditingController name_Controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    // Load data directly without login
    start=0;
    query="";
    load_data();
  }
  void load_data(){
      items({"limit":limit,'start':start,'query':query}, (r) {
        res=r;
        print(res);
        total=res["total"];
        var newRows=<TableRow>[];
        newRows.add(TableRow(
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                border: Border(bottom: BorderSide(width: 2.0, color: Colors.blue.shade300)),
              ),
              children: 
                [
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                    child: Text(
                      "ID",
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                    child: Text(
                      "编号",
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                    child: Text(
                      "名称",
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                    child: Text(
                      "规格",
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                    child: Text(
                      "单位",
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                    child: Text(
                      "操作",
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
                    ),
                  ),
                ]
              ));
        for(var i=0;i<res["data"].length;i++){
          bool isEven = i % 2 == 0;
          newRows.add(TableRow(
              decoration: BoxDecoration(
                color: isEven ? Colors.white : Colors.grey.shade50,
              ),
              children: ([
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                  child: Text(res["data"][i]["id"].toString(), style: TextStyle(fontSize: 13.0)),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                  child: Text(res["data"][i]["bh"]==null?"":res["data"][i]["bh"], style: TextStyle(fontSize: 13.0)),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                  child: Text(res["data"][i]["name"]==null?"":res["data"][i]["name"], style: TextStyle(fontSize: 13.0)),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                  child: Text(res["data"][i]["guige"]==null?"":res["data"][i]["guige"], style: TextStyle(fontSize: 13.0)),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                  child: Text(res["data"][i]["danwei"]==null?"":res["data"][i]["danwei"], style: TextStyle(fontSize: 13.0)),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      ElevatedButton.icon(
                        onPressed: (){doEdit2(i);},
                        icon: Icon(Icons.edit, size: 14.0),
                        label: Text("编辑", style: TextStyle(fontSize: 12.0)),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue.shade400,
                          foregroundColor: Colors.white,
                          padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
                          minimumSize: Size(80, 36),
                        ),
                      ),
                      ElevatedButton.icon(
                        onPressed: (){doDelete(i);},
                        icon: Icon(Icons.delete, size: 14.0),
                        label: Text("删除", style: TextStyle(fontSize: 12.0)),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red.shade400,
                          foregroundColor: Colors.white,
                          padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
                          minimumSize: Size(80, 36),
                        ),
                      ),
                    ]
                  ),
                ),
              ]),
            ));
        }
        setState((){
          rows=newRows;
        });
      }, err_treat);
  }
  void doPrev(){
    if(res==null) return;
    start-=limit;
    if(start<0) start=0;
    load_data();
  }
  void doGo(){
    if(res==null) return;
    start=int.parse(at_Controller.text);
    if(start<0) start=0;
    load_data(); 
  }
  void do_search(){
    start=0;
    query=search_Controller.text;
    load_data();
  }
  void doNext(){
    if(res==null) return;
    start+=limit;
    if(start>res["total"]-limit) start=res["total"]-limit;
    if(start<0) start=0;
    load_data();
  }
  void do_new() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CreateItemScreen(),
      ),
    );
    if (result == true) {
      load_data(); // Refresh the list after creating new item
    }
  }
  void puti(id,name){
    put("/rest/Item/", {"id":id,"name":name},(r){
      print(r);
    }, (e){
      print(e);
    });
  }
  void deletei(id, [Function()? successCallback, Function()? errorCallback]){
    delete1("/rest/Item/", {"id":id},(r){
      print(r);
      successCallback?.call();
    }, (e){
      print(e);
      errorCallback?.call();
    });
  }
  void doDelete(i) async{
    showDialog(context: context, builder: (BuildContext context){
      return     Dialog(
      child: Container(
        height: 300,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FlutterLogo(size: 150,),
            Text(res["data"][i]["name"],style:TextStyle(fontSize: 20),),
            ElevatedButton(
            onPressed: (){
              deletei(res["data"][i]["id"], () {
                load_data(); // Refresh the list after deleting item
              });
              Navigator.of(context).pop();
            }, child: Text("Ok")),
            ElevatedButton(
            onPressed: (){
              Navigator.of(context).pop();

            }, child: Text("Cancel"))
          ],
        ),
      ),
      );
    });
  }
  void doEdit2(i) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ItemArgumentsScreen(),
        settings: RouteSettings(
          arguments: ItemArguments(
            res["data"][i]["id"],
            res["data"][i]["name"],
            guige: res["data"][i]["guige"] ?? "",
            danwei: res["data"][i]["danwei"] ?? "",
          ),
        ),
      ),
    );
    if (result == true) {
      load_data(); // Refresh the list after editing item
    }
  }
  //void doEdit(i) async{

  //  showDialog(context: context, builder: (BuildContext context){
  //    return     Dialog(
  //    child: Container(
  //      height: 300,
  //      child: Column(
  //        mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //        children: [
  //          FlutterLogo(size: 150,),
  //          Text(res["data"][i]["name"],style:TextStyle(fontSize: 20),),
  //          TextField(controller:  name_Controller,
  //            decoration: InputDecoration(labelText: "name"),
  //            ),
  //          ElevatedButton(
  //          onPressed: (){
  //            puti(res["data"][i]["id"],res["data"][i]["name"]);
  //            Navigator.of(context).pop();
  //            //delete 
  //          }, child: Text("Ok")),
  //          ElevatedButton(
  //          onPressed: (){
  //            Navigator.of(context).pop();

  //          }, child: Text("Cancel"))
  //        ],
  //      ),
  //    ),
  //    );
  //  });  
  //}
  void enterRoute(){
    var result = Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                return AlignRoute();
              },
            ),
          );
          print("路由返回值: $result");
  }

  void doClear() {

    setState(() {
      rows=[TableRow(
              decoration: BoxDecoration(color: Colors.grey[200]),
              children: 
                [
                  Text("用户"),
                  Text("仪器型号"),
                  Text("仪器编号"),
                ]
              )];
    });
  }
  _addPadding(List<Widget> w) {
    return w
        .map((e) => Padding(
              padding: EdgeInsets.all(6),
              child: e,
            ))
        .toList();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('备件'),
      ),
      body: Container(
        padding: EdgeInsets.all(20.0),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(bottom: 20.0),
                padding: EdgeInsets.all(12.0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.1),
                      spreadRadius: 1,
                      blurRadius: 3,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    
                    Expanded(
                      child: TextField(
                        controller: search_Controller,
                        decoration: InputDecoration(
                          labelText: "名称搜索",
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.search),
                          contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.0),
                    ElevatedButton.icon(
                      icon: Icon(Icons.search),
                      label: Text("搜索"),
                      onPressed: do_search,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.grey.shade700,
                        foregroundColor: Colors.white,
                      ),
                    ),
                    SizedBox(width: 12.0),
                    ElevatedButton.icon(
                      icon: Icon(Icons.add),
                      label: Text("新建"),
                      onPressed: do_new,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green.shade600,
                        foregroundColor: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Container(
                  margin: EdgeInsets.only(top: 20.0),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.0),
                    border: Border.all(color: Colors.blue.shade200, width: 1.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.1),
                        spreadRadius: 1,
                        blurRadius: 3,
                        offset: Offset(0, 2), // changes position of shadow
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Table(
                      border: TableBorder(
                        horizontalInside: BorderSide(color: Colors.grey.shade200, width: 1.0),
                      ),
                      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                      columnWidths: const <int, TableColumnWidth>{
                        0: FixedColumnWidth(80),  // id
                        1: FixedColumnWidth(120), // bh
                        2: FixedColumnWidth(160), // name
                        3: FixedColumnWidth(120), // spec
                        4: FixedColumnWidth(100), // unit
                        5: FixedColumnWidth(200), // actions
                      },
                      children: rows,
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    width: 150,
                    child: TextField(
                      controller: at_Controller,
                      decoration: InputDecoration(labelText: "name"),
                    ),
                  ),
                  SizedBox(width: 16.0),
                  ElevatedButton(
                    onPressed: doGo,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green.shade600,
                      foregroundColor: Colors.white,
                      minimumSize: Size(80, 45),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 4,
                      textStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                    ),
                    child: Text("Go"),
                  ),
                  SizedBox(width: 12.0),
                  ElevatedButton(
                    onPressed: doPrev,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green.shade600,
                      foregroundColor: Colors.white,
                      minimumSize: Size(80, 45),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 4,
                      textStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                    ),
                    child: Text("Prev"),
                  ),
                    SizedBox(width: 16.0),
                  Text(
                    "${start.toString()}/${total.toString()}",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey.shade700,
                    ),
                  ),
                  SizedBox(width: 16.0),
                  ElevatedButton(
                    onPressed: doNext,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green.shade600,
                      foregroundColor: Colors.white,
                      minimumSize: Size(80, 45),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 4,
                      textStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                    ),
                    child: Text("Next"),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

